const { request } = require("express");
const {Log} = require('./logger.js')

var ProxyPortServer =require('./ProxyPortServer')
const MainServer = require('./MainServer')
const DataServer = require('./DataServer')

const express = require('express')
const app = express()
const port = 4008

// 关闭服务代理端口
app.get("/admin/closeProxyPort/:port", (req, res)=>{
    Log.info(req.path)
    var port = req.params.port;
    if( !isNaN(port)){
        var pssid = ProxyPortServer.closeProxyPortServer(port)
        res.send("proxyport server closed "+pssid)
    }else{
        res.send("port is not number")
    }
})

// 添加服务带来端口 lport, node , nport 三个参数
app.get("/admin/addProxyPort", (req, res)=>{
    Log.info(req.path)
    var {lport, node, nport} = req.query
    if(lport && node && nport){
        Log.info("try to add config")

        var pssid = ProxyPortServer.closeProxyPortServer(lport)
        if(pssid){
            setTimeout(() => {
                var  pps = new ProxyPortServer(lport, node, nport, MainServer.instance, DataServer)
                pps.start()
            }, 1000);
        }else{
            var  pps = new ProxyPortServer(lport, node, nport, MainServer.instance, DataServer)
            pps.start()
            // return pps.getProxyServerID()
        }

        // var ppid = ProxyPortServer.addProxyConfig(lport, node, nport)
        res.send("start proxyserver on port "+ lport )
    }else{
        res.send("lport node nport params maybe error")
    }
})

// 列出所有代理的端口
app.get("/admin/listProxyPort",(req, res)=>{
    Log.info(req.path)
    var list = ProxyPortServer.getAllProxyPortServerID()
    Log.info("list ppsid %s", JSON.stringify(list))
    res.json(list)
})

app.listen(port, ()=>{
    Log.info("WebServer listen on %s", port)
})
